#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
验证ChromaDB路径修复是否有效
"""

import asyncio
import sys
import os
from pathlib import Path

# 添加src目录到Python路径
src_path = os.path.join(os.path.dirname(__file__), 'src')
sys.path.insert(0, src_path)

from src.config import load_config
from src.mcp.tools import MCPTools
from src.core.context_orchestrator import ContextOrchestrator

async def verify_chromadb_fix():
    """验证ChromaDB路径修复"""
    print("=== 验证ChromaDB路径修复 ===")
    
    try:
        # 1. 检查配置
        config = load_config()
        chromadb_config = config.get('databases', {}).get('chromadb', {})
        persist_directory = chromadb_config.get('persist_directory', './chroma_db')
        print(f"✓ 配置中的persist_directory: {persist_directory}")
        
        # 2. 检查数据仓库路径
        project_root = Path(__file__).parent
        chroma_path = project_root / persist_directory.lstrip('./')
        print(f"✓ 实际ChromaDB路径: {chroma_path}")
        print(f"✓ 路径是否存在: {chroma_path.exists()}")
        
        if chroma_path.exists():
            subdirs = list(chroma_path.iterdir())
            print(f"✓ 数据仓库包含 {len(subdirs)} 个子目录")
        
        # 3. 初始化MCP工具
        print("\n--- 初始化MCP工具 ---")
        orchestrator = ContextOrchestrator(config)
        await orchestrator.initialize()
        
        mcp_tools = MCPTools(orchestrator)
        
        # 4. 测试conversation_search
        print("\n--- 测试conversation_search ---")
        search_params = {
            "query": "王者荣耀",
            "user_id": "default_user",
            "limit": 5
        }
        
        result = await mcp_tools._conversation_search(search_params)
        print(f"✓ 搜索结果: {result}")
        
        if result and 'results' in result and result['results']:
            print(f"✓ 找到 {len(result['results'])} 条对话")
            for i, conv in enumerate(result['results'][:2]):
                print(f"  对话 {i+1}: {conv.get('title', 'N/A')} (相似度: {conv.get('similarity', 'N/A')})")
        else:
            print("⚠ 未找到匹配的对话")
        
        # 5. 关闭连接
        await orchestrator.close()
        print("\n✓ 验证完成")
        
    except Exception as e:
        print(f"❌ 验证失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        # 清理资源
        if 'orchestrator' in locals() and hasattr(orchestrator, 'close'):
            await orchestrator.close()
        elif 'orchestrator' in locals() and hasattr(orchestrator, 'db_manager'):
            await orchestrator.db_manager.close()

if __name__ == "__main__":
    asyncio.run(verify_chromadb_fix())